package com.xrkj.b2c.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * <B>系统名称：</B><BR>
 * <B>模块名称：</B><BR>
 * <B>中文类名：</B>Unicode编码工具类<BR>
 * <B>概要说明：</B><BR>
 * @author 赵子靖
 * @since 2018年07月15日
 */
public class UnicodeUtil {
	
   private final static String REGEX = "[\\w\\d\\-\\s~`!@#$%^&*()_+\\?\\.,\\|\\[\\]{}''\\\"\\\":;<>/\\\\]";
	
	/**
	 * 该方法用于将字符串进行Unicode编码
	 * 
	 * @param content
	 *            ----> 需要Unicode编码的字符串
	 * @return 返回经Unicode编码的字符串
	 */
	public static String unicode(String content) {

		StringBuffer strBuf = new StringBuffer();
		for (int i = 0; i < content.length(); i++) {
			char c = content.charAt(i);
			Matcher matcher = Pattern.compile(REGEX).matcher(
					String.valueOf(c));
			if (matcher.matches()) {
				strBuf.append(c);
			} else {
				strBuf.append("\\u").append(Integer.toHexString(c));
			}
		}
		return strBuf.toString();
	}

	/**
	 * 该方法用于将经Unicode编码的字符串还原
	 * 
	 * @param unicodeStr
	 *            ----> 经Unicode编码的字符串
	 * @return 返回原始字符串
	 */
	public static String unicodeReverse(String unicodeStr) {

		Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{2,4}))");
		Matcher matcher = pattern.matcher(unicodeStr);
		char ch;
		while (matcher.find()) {
			ch = (char) Integer.parseInt(matcher.group(2), 16);
			unicodeStr = unicodeStr.replace(matcher.group(1), ch + "");
		}
		return unicodeStr;
	}

	/*
	 * 测试
	 */

	public static void main(String[] args) {

		String text = "技术 经理 A-10_!@#`~$%^&*()_+-[]{}'';:?/.,<>\\";

		String encode = UnicodeUtil.unicode(text);
		String decode = UnicodeUtil.unicodeReverse(encode);

		System.out.println("原文：" + text);
		System.out.println("编码：" + encode);
		System.out.println("解码：" + decode);
	}
}
